
#region Imported NameSpaces
using System;
using System.Collections;
using System.Data;

using BO = PHSRAG.Insight21.BusinessObjects;
using Utility = PHSRAG.Utility;
using ICachePolicy = PHSRAG.Insight21.Policy.ICachePolicy;
using DataAccess = PHSRAG.Utility.DataAccess;
#endregion

namespace PHSRAG.Insight21.Humans
{
	/// <summary>
	/// A collection class to hold Drug objects.
	/// Functions exist to load the drug object according to the search parameters and add 
	/// it to drug collection and to get the drug types to be filled in the combobox.
	/// </summary>
	public class Drugs:BO.BusinessObject
	{
		#region Private instance variables
		private ArrayList drugList;
        private string sortBy;
        #endregion

		#region private constant cacheKey
		private const string DrugsKey = "DrugsKey_A0D81ADF-15D7-4e7b-96E0-451E7FB101F8";
		private const string DrugCollectionTableName = "DrugCollection";
		#endregion

        #region SortByColumn constants
        /// <summary>
        /// Constants for setting the sortby column when getting the datarow arraylist
        /// </summary>
        public class SortByColumn
        {
            public const string ItemName = "sItemName";
            public const string GenericName = "sGenericName";
            public const string MarketingName = "sPreGenericName";
        }
        #endregion
        
        #region public properties
		/// <summary>Gets/Sets the drug object Collection </summary>
		public ArrayList DrugList
		{
			get 
			{
				if (drugList==null)
				{
					drugList=GetList();
				}
				return drugList;
			}
			set {drugList=value;}
		}

        public string SortBy
        {
            get { return sortBy; }
            set
            {
                if (sortBy != value)
                    drugList = null;
                sortBy = value;
            }
        }
        #endregion

		#region Public override methods

		#region caching
		/// <summary>
		/// Cache the current Object (Drugs)using the prevalent cache policy.
		/// </summary>
		public override void Cache()
		{
			CachePolicy.Cache(DrugsKey, this);
		}

		/// <summary>
		/// Remove an object from the cache using the prevalent cache policy and its cacheKey .
		/// </summary>
		public override void UnCache()
		{
			CachePolicy.UnCache(DrugsKey);
		}
		#endregion

		/// <summary>
		/// Loads the dataContainer with the results(Drugs)obtained using the search criteria
		/// </summary>
		/// <param name="rexConnection">Legacy database connection string</param>
		/// <param name="args">Search parameter values </param>
		public override void Load (string rexConnection,  params object[] args )
		{
			try
			{
				if (args.Length != 8)
				{
					throw new Exception("Mismatch in the parameter supplied to Drugs.Load()");
				}
				else 
				{
					drugList = null;

					System.Data.SqlClient.SqlParameter[] parameters =
						DataAccess.BuildSqlParameterArray(
						"@bSchedule2",		  SqlDbType.Bit,		(bool)args[(int)DrugMembers.Schedule2],     //Value to this parameter(@bSchedule) not known
						"@bContainsWord",	  SqlDbType.Bit,		(bool)args[(int)DrugMembers.ContainsWord]); //Value to this parameter(@bContainsWord) not known

					if ( string.Empty != (string)args[(int)DrugMembers.ItemName] )
					{
						DataAccess.AppendToSqlParameterArray( ref parameters, "@sItemName", SqlDbType.VarChar, args[(int)DrugMembers.ItemName] );
					}

					if ( string.Empty != (string)args[(int)DrugMembers.GenericName] )
					{
						DataAccess.AppendToSqlParameterArray( ref parameters, "@sGenericName", SqlDbType.VarChar, args[(int)DrugMembers.GenericName] );
					}

					if ( string.Empty != (string)args[(int)DrugMembers.PreGenericName] )
					{
						DataAccess.AppendToSqlParameterArray( ref parameters, "@sPreGenericName", SqlDbType.VarChar,	args[(int)DrugMembers.PreGenericName] );
					}

					if ( string.Empty != (string)args[(int)DrugMembers.BiologicClass] )
					{
						DataAccess.AppendToSqlParameterArray( ref parameters, "@sDrugBiologicClass",SqlDbType.VarChar, args[(int)DrugMembers.BiologicClass] );
					}

					if ( string.Empty != (string)args[(int)DrugMembers.Manufacturer] )
					{
						DataAccess.AppendToSqlParameterArray( ref parameters, "@sManufacturer", SqlDbType.VarChar, args[(int)DrugMembers.Manufacturer] );
					}

					if ( string.Empty != (string)args[(int)DrugMembers.Type] )
					{
						DataAccess.AppendToSqlParameterArray( ref parameters, "@sItemType", SqlDbType.VarChar,	args[(int)DrugMembers.Type] );
					}

					DataContainer = DataAccess.GetDataSet(rexConnection, "spIRBDrugBiologicSearch", parameters );

					if(DataContainer.Tables.Count > 0)
					{
						DataContainer.Tables[0].TableName = DrugCollectionTableName;
					}
					else
					{
						throw new Exception("Failed to load drugs. The stored procedure returned incorrect results.");
					}
				}						
			}
			catch(Exception ex)
			{
				throw new Exception("Failed to load Drug(s). Error occurred while executing the Load() of the Drugs object", ex);
			}
		}

		#endregion

		#region constructor
		/// <summary>
		/// Constructs a new Drugs object based on the Cache Policy passed in as a parameter. 
		/// </summary>
		/// <param name="cachePolicy">available cahche policy</param>
		public Drugs(ICachePolicy cachePolicy): base(cachePolicy)
		{	
			
		}
		#endregion

		#region public methods
		/// <summary>
		/// Gets the drug types.
		/// </summary>
		/// <param name="rexConnection">Legacy database connection string</param>
		/// <returns>ArrayList of drug types</returns>
		public ArrayList GetDrugTypes(string rexConnection)
		{
			try
			{
				System.Data.DataTable dataTable= DataAccess.GetDataTable(rexConnection, "spListValuesGetByType",
					DataAccess.BuildSqlParameterArray("@sFieldName", SqlDbType.VarChar, "sItemType"
					,"@sValue1",SqlDbType.VarChar,DBNull.Value
					,"@sValue2",SqlDbType.VarChar,DBNull.Value
					,"@sValue3",SqlDbType.VarChar,DBNull.Value
					,"@sValue4",SqlDbType.VarChar,DBNull.Value
					,"@nReturnField",SqlDbType.Int,DBNull.Value
					,"@sPSCode",SqlDbType.VarChar,DBNull.Value
					,"@sType",SqlDbType.VarChar,DBNull.Value
					));	
				if((dataTable!=null)&&(dataTable.Rows.Count!=0))
				{
					ArrayList drugTypes=new ArrayList();		
					foreach (DataRow row in dataTable.Rows)
					{
						string drugType = row["sValue"].ToString();
						if (drugType.ToLower() != "device")
							drugTypes.Add(drugType);
					}
					return drugTypes;
				}
			}
			catch(Exception ex)
			{
				throw new Exception("Failed to get the Drug types.", ex);
			}
			return null;
		}
		#endregion

		#region private methods
		/// <summary> Gets the collection of drug objects </summary>
		/// <returns>Arraylist of drug object</returns>
		private ArrayList GetList()
		{
			ArrayList drugList = null;
			if ((DataContainer != null) && (DataContainer.Tables.Count != 0))
			{
				drugList=new ArrayList();

                DataTable drugsTable = null;
                if (sortBy != string.Empty)
                {
                    drugsTable = DataContainer.Tables[DrugCollectionTableName];
                    drugsTable.DefaultView.Sort = sortBy;
                }
                for (int i = 0; i < drugsTable.DefaultView.Count; i++)
                {
                    DataRow dataRow = drugsTable.DefaultView[i].Row;
                    drugList.Add(new Drug(CachePolicy, dataRow));
                }
            }
			return drugList;
			
		}
		#endregion 
        
		#region Enumerations
		/// <summary>Drug member enumerations</summary>
		public enum DrugMembers
		{
			ItemName,
			GenericName,
			PreGenericName,
			BiologicClass,
			Manufacturer,
			Type,
			Schedule2,
			ContainsWord,
			LegacyName
		}
		#endregion
		
	}
}
